<template>
    <div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="点位管理" name="first">
                <div style="display: inline-block;">
                    <div style="display: inline-block;margin: 5px;">
                        <span>类别：</span>
                        <el-select v-model="queryForm.type" style="width:150px;margin-left: 10px;">
                            <el-option v-for="item in statesnum" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>&nbsp;&nbsp;
                    </div>


                    <el-button style='margin-left:15px;' size="mini" type="primary" icon="document"
                        @click="homeSelect">查询
                    </el-button>
                    <el-button style='margin-left:15px;' size="mini" type="primary" icon="document" @click="cleans">重置
                    </el-button>
                    <el-button style='margin-left:15px;' size="mini" type="primary" icon="document" @click="addBtn()">添加
                    </el-button>
                </div>
                <el-table v-loading="tableDataLoading" :data="homeData.list">
                    <el-table-column fixed prop="id" label="编号" width="80" />
                    <el-table-column prop="area" label="区域" />


                    <el-table-column prop="name" label="详细地址" />
                    <el-table-column prop="lat" label="经度" width="180"></el-table-column>
                    <el-table-column prop="lng" label="纬度" width="180"></el-table-column>
                    <el-table-column prop="type" label="类别" width="100">
                        <template slot-scope="scope">
                            <div>{{ seclectType(scope.row.type)}}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200" fixed="right">
                        <template slot-scope="scope">
                            <el-button size="mini" type="primary" style="margin: 5px;"
                                @click="looking(scope.row)">查看</el-button>
                            <el-button style='margin:5px;' size="mini" type="primary" @click="compile(scope.row)">删除
                            </el-button>

                        </template>
                    </el-table-column>
                </el-table>
                <div style="text-align: center;margin-top: 10px;">
                    <el-pagination @size-change="handleSizeChange1" @current-change="handleCurrentChange1"
                        :page-sizes="[10, 20, 30, 40]" :page-size="size" :current-page="page"
                        layout="total,sizes, prev, pager, next,jumper" :total="homeData.totalCount">
                    </el-pagination>
                </div>

            </el-tab-pane>




            <!-- 添加/修改 任务 -->
            <el-dialog :title="titles" :visible.sync="dialogFormVisibleRw" center width="50%">

                <div style="margin-bottom: 10px;">
                    <span style="width: 200px;display: inline-block;text-align: right;">搜索：</span>
                    <el-select v-model="value" filterable remote reserve-keyword placeholder="请输入关键词"
                        :remote-method="remoteMethod" :loading="loading" style="width:45%;" @change="SelectStartPoint">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </div>
                <div style="margin-bottom: 10px;">
                    <span style="width: 200px;display: inline-block;text-align: right;">经度：</span>
                    <el-input v-model="tableData.lng" style="width:45%;" disabled placeholder="经度">
                    </el-input>
                </div>
                <div style="margin-bottom: 10px;">
                    <span style="width: 200px;display: inline-block;text-align: right;">纬度：</span>
                    <el-input v-model="tableData.lat" style="width:45%;" disabled placeholder="纬度">
                    </el-input>
                </div>
                <div style="margin-bottom: 10px;">
                    <span style="width: 200px;display: inline-block;text-align: right;">区域：</span>
                    <el-input v-model="tableData.area" style="width:45%;" disabled placeholder="区域"></el-input>
                </div>
                <div style="margin-bottom: 10px;">
                    <span style="width: 200px;display: inline-block;text-align: right;">详细地址：</span>
                    <el-input v-model="tableData.name" style="width:45%;" disabled placeholder="详细地址"></el-input>
                </div>
                <div style="margin-bottom: 10px;">
                    <span style="display: inline-block;width: 200px;text-align: right;">类别：</span>
                    <el-select v-model="tableData.type" style="width:45%;">
                        <el-option v-for="item in statesnum" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </div>


                <div id="map" class="map-wrapper"></div>



                <div slot="footer" class="dialog-footer" style="margin-top: 30px;text-align: center;">
                    <el-button @click="dialogFormVisibleRw=false">取 消</el-button>
                    <el-button type="primary" @click="addmissionNoticeTo()">确 定</el-button>
                </div>


            </el-dialog>



        </el-tabs>
    </div>
</template>

<script>

    import 'quill/dist/quill.core.css'
    import 'quill/dist/quill.snow.css'
    import 'quill/dist/quill.bubble.css'
    import axios from 'axios';
    import {
        jsonp
    } from 'vue-jsonp'
    export default {
        data() {
            return {
                size: 10,
                page: 1,
                state: '',
                limit: 10,
                activeName: 'first',
                tableDataLoading: true,
                homeData: [],
                statesnum: [
                    {
                        value: 0,
                        label: '快递柜'
                    },
                    {
                        value: 1,
                        label: '仓库'
                    },
                    {
                        value: 2,
                        label: '驿站'
                    },
                    {
                        value: 3,
                        label: '中转站'
                    }
                ],
                // x新的
                indentState: 0, //任务状态
                dialogFormVisible: false,
                // 添加/修改任务
                dialogFormVisibleRw: false,
                titles: '',
                map: null,
                MAP_KEY: 'NMEBZ-UPS3C-VBQ2B-ADNFP-LX6QH-NRBP5', // 腾讯地图API Key
                tableData: {
                    area: undefined,
                    id: undefined,
                    lat: undefined,
                    lng: undefined,
                    name: undefined,
                    type: undefined, //0:快递柜，1：仓库
                    areaCode: undefined,
                },
                queryForm: {
                    type: undefined
                },
                options: [],
                value: [],
                pointList: [],
                loading: false,
                centerLat: '',
                centerLng: '',
            }
        },
        methods: {

            remoteMethod(query) {

                this.loading = true;
                jsonp(`https://apis.map.qq.com/ws/place/v1/search?key=${this.MAP_KEY}&output=jsonp&keyword=${encodeURI(query)}&boundary=nearby(${this.centerLat},${this.centerLng},1000,1)`).then(res => {
                    if (query !== '') {

                        setTimeout(() => {
                            this.loading = false;
                            this.pointList = res.data;
                            this.options = res.data.map(item => {
                                return { value: `${item.id}`, label: `${item.title}` };
                            });
                        }, 200);
                    } else {
                        this.options = [];
                    }
                }).catch(error => {
                    console.log('error', error)
                });


            },


            SelectStartPoint(row) {
                let point = this.pointList.find(it => it.id == row);
                this.tableData = {
                    area: point.ad_info.province + point.ad_info.city + point.ad_info.district,
                    id: '',
                    lat: point.location.lat,
                    lng: point.location.lng,
                    name: point.title,
                    type: '', //0:快递柜，1：仓库
                    areaCode: point.ad_info.adcode,
                }
            },

            handleSizeChange1(val) {
                this.limit = val
                this.homeSelect()
            },
            handleCurrentChange1(val) {
                this.page = val
                this.homeSelect()
            },


            handleClick(tab, event) { },



            // 删除
            compile(row) {
                this.$confirm(`确定删除当前点位?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http({
                        url: this.$http.adornUrl('point/delete'),
                        method: 'post',
                        data: this.$http.adornData([row.id])
                    }).then(({
                        data
                    }) => {
                        if (data.code == 0) {
                            this.$message({
                                message: '删除成功',
                                type: 'success',
                                duration: 1500,
                                onClose: () => {
                                    this.homeSelect()
                                }
                            })
                        } else {
                            this.$notify({
                                title: '提示',
                                duration: 1800,
                                message: data.msg,
                                type: 'warning'
                            })
                        }

                    })
                })
            },



            //分析类别名称
            seclectType(type) {
                if (type != undefined || type != null || type != '') {
                    return this.statesnum.find(it => it.value == type).label
                } else {
                    return ''
                }
            },

            // 查看
            looking(row) {
                this.titles = '查看点位'
                this.dialogFormVisibleRw = true
                this.options = [];
                this.value = [];
                this.tableData = row
                this.$nextTick(() => {
                    this.initMap(row.lng, row.lat);
                })

            },

            // 获取数据列表
            homeSelect() {
                this.tableDataLoading = true
                this.$http({
                    url: this.$http.adornUrl(`point/list`),
                    method: 'get',
                    params: this.$http.adornParams({
                        'page': this.page,
                        'limit': this.limit,
                        'type': this.queryForm.type
                    })
                }).then(({
                    data
                }) => {
                    this.tableDataLoading = false
                    if (data.code == 0) {
                        this.homeData = data.page
                    }
                })
            },

            // 重置
            cleans() {
                this.queryForm.type = undefined;
                this.page = 1;
                this.limit = 10;
                this.homeSelect()
            },





            // 添加/修改 任务
            addBtn() {
                this.titles = '添加点位'
                this.options = [];
                this.value = [];
                this.tableData = {
                    area: undefined,
                    id: undefined,
                    lat: undefined,
                    lng: undefined,
                    name: undefined,
                    type: undefined, //0:快递柜，1：仓库
                    areaCode: undefined,
                }

                this.dialogFormVisibleRw = true
                this.initMap();// 默认洛阳智能科技产业园
            },
            // 确定添加/修改
            addmissionNoticeTo() {

                if (this.tableData.name == undefined || this.tableData.name == '') {
                    this.$message.warning('请选择地点');
                    return;
                }

                if (this.tableData.type.length == 0) {
                    this.$message.warning('请选择类别');
                    return;
                }

                if (this.tableData.id) {
                    this.$http({
                        url: this.$http.adornUrl(`point/update`),
                        method: 'post',
                        data: this.$http.adornData(this.tableData)
                    }).then(({ data }) => {
                        if (data.code == 0) {
                            this.$message.success('修改成功');
                        }
                        this.homeSelect();
                    })
                } else {
                    this.$http({
                        url: this.$http.adornUrl(`point/save`),
                        method: 'post',
                        data: this.$http.adornData(this.tableData)
                    }).then(({ data }) => {

                        if (data.code == 0) {
                            this.$message.success('添加成功');
                        }
                        this.homeSelect();
                    })
                }
                this.dialogFormVisibleRw = false
            },



            // 初始化地图
            initMap(lng, lat) {
                var geolocation = new qq.maps.Geolocation(this.MAP_KEY, "点位管理");
                geolocation.getIpLocation(this.showPosition, this.showErr);
            },

            showPosition(position) {
                this.centerLat = position.lat;
                this.centerLng = position.lng;
                let lat = position.lat;
                let lng = position.lng;

                // 确定地图中心点
                let centerLat = lat || 34.672857153159846;
                let centerLng = lng || 112.43718266487122;
                // 初始化地图
                this.map = new qq.maps.Map(document.getElementById('map'), {
                    center: new qq.maps.LatLng(centerLat, centerLng),
                    zoom: 12,
                    mapTypeId: qq.maps.MapTypeId.ROADMAP
                });

                // 如果提供了坐标，则添加标记
                if (lng && lat) {
                    const marker = new qq.maps.Marker({
                        position: new qq.maps.LatLng(centerLat, centerLng),
                        map: this.map
                    });
                    this.currentMarker = marker;
                }



                // 添加点击事件监听器（仅在添加/编辑模式下）
                qq.maps.event.addListener(this.map, 'click', (event) => {
                    // 清除之前的标记
                    if (this.currentMarker) {
                        this.currentMarker.setMap(null);
                    }


                    // 创建新标记
                    this.currentMarker = new qq.maps.Marker({
                        position: event.latLng,
                        map: this.map,
                    });

                    this.currentMarker.setAnimation(qq.maps.MarkerAnimation.DOWN);
                    this.value = []
                    // 获取地址信息
                    this.getAddressByLatLng(event.latLng);
                });
            },
            showErr(e) {
                console.log("定位失败", e);
                this.$message.error("定位失败，请手动选择位置或检查网络设置");
            },


            // 根据经纬度获取地址信息
            getAddressByLatLng(latLng) {
                let data = `${latLng.lat},${latLng.lng}`;
                jsonp(`https://apis.map.qq.com/ws/geocoder/v1/?location=${data}&key=${this.MAP_KEY}&output=jsonp`, {
                    myCustomUrlParam: 'veryNice'
                }).then(res => {
                    if (res.status === 0) {
                        const address_component = res.result.address_component;
                        this.tableData.lat = res.result.location.lat;
                        this.tableData.lng = res.result.location.lng;
                        this.tableData.area = address_component.province + address_component.city + address_component.district;
                        this.tableData.name = res.result.formatted_addresses.recommend;
                        this.tableData.areaCode = res.result.ad_info.adcode

                        this.currentMarker.setTitle(this.tableData.name)
                    } else {
                        this.$message.error('未找到该地址，请重新输入');
                    }
                }).catch(error => {
                    console.log('error', error)
                });
            },


        },
        mounted() {
            this.homeSelect()
        }
    }
</script>

<style scoped>
    .customWidth {
        width: 80% !important;
    }



    .cards {
        padding: 0 8px;
        margin-bottom: 15px;
    }



    .bannerbtn {
        display: flex;
        border-top: none !important;
        border: 1px solid #e8e8e8;
        padding: 11px;
        font-size: 14px;
        color: #3E8EF7;
    }

    .bannerbtn a {
        flex: 1;
        text-align: center;
        color: #3E8EF7 !important;
        text-decoration: none;
    }

    .imgs {
        position: relative;
        border-radius: 6px;
        width: 148px;
        height: 148px;
        margin-right: 10px;
        display: inline-block;
    }

    .dels {
        position: absolute;
        top: 0;
        left: 0;
        display: none;
    }

    .dels .el-icon-delete {
        line-height: 148px;
        padding-left: 58px;
        font-size: 25px;
        color: #fff;
    }

    .imgs:hover .dels {
        width: 100%;
        height: 100%;
        background: #000;
        display: block;
        opacity: 0.5;
    }

    .bqList {
        padding: 4px 14px;
        margin: 4px;
        border: 1px solid #efefef;
        font-size: 12px;
        color: #999;
        border-radius: 4px;
        margin-right: 15px;
    }

    .delss {
        display: none;
        position: relative;
    }

    .delss .el-icon-delete {
        position: absolute;
        top: 0;
    }

    .bqList:hover .delss {
        display: initial;
        opacity: 0.5;

    }

    .map-wrapper {
        width: 70%;
        height: 300px;
        margin-left: 100px;
    }
</style>